package net.gyapp.markim.module.message.adapter;

import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.easyder.wrapper.utils.LogUtils;
import com.lqr.audio.AudioPlayManager;
import com.lqr.audio.IAudioPlayListener;
import com.lqr.emoji.MoonUtils;

import net.gyapp.markim.R;
import net.gyapp.markim.WrapperApplication;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.entity.MessageEntity;
import net.gyapp.markim.module.basic.base.BaseRecyclerHolder;
import net.gyapp.markim.module.message.ImagePreviewActivity;
import net.gyapp.markim.module.message.bean.VoiceBean;
import net.gyapp.markim.utils.AudioPlayerManager;
import net.gyapp.markim.utils.AudioRecorderManager;
import net.gyapp.markim.utils.CommonTools;
import net.gyapp.markim.utils.DownloadManager;

import org.jim.common.packets.ChatType;
import org.jim.common.packets.Command;
import org.jim.common.packets.MsgType;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.winds.widget.autolayout.utils.AutoUtils;
import me.winds.widget.usage.ToastView;

/**
 * Auther:  winds
 * Email:   heardown@163.com
 * Date:    2018/7/29.
 * Desc:
 */

public class ConversationAdapter extends BaseQuickAdapter<MessageEntity, BaseRecyclerHolder> {

    private static final int MSG_SEND_TEXT = R.layout.item_chat_text_send;
    private static final int MSG_RECEIVE_TEXT = R.layout.item_chat_text_receive;
    private static final int MSG_SEND_IMAGE = R.layout.item_chat_image_send;
    private static final int MSG_RECEIVE_IMAGE = R.layout.item_chat_image_receive;
    private static final int MSG_SEND_AUDIO = R.layout.item_chat_audio_send;
    private static final int MSG_RECEIVE_AUDIO = R.layout.item_chat_audio_receive;
    private static final int MSG_SEND_VIDEO = R.layout.item_chat_video_send;
    private static final int MSG_RECEIVE_VIDEO = R.layout.item_chat_video_receive;
    private static final int MSG_SEND_STICKER = R.layout.item_chat_sticker_send;
    private static final int MSG_RECEIVE_STICKER = R.layout.item_chat_sticker_receive;
    private static final int MSG_NOTIFICATION = R.layout.item_chat_notification;
    private static final int MSG_UNKNOW = R.layout.item_chat_no_support_msg_type;


    public int currentPosition = -1;

    public ConversationAdapter() {
        super(null);
    }

    public void setChatType(ChatType type) {

    }

    public void setAdapterData(List<MessageEntity> list) {
        setNewData(list);
        downloadVoiceFile(list);
    }

    public void addAdapterHeadData(List<MessageEntity> list) {
        if (list != null && list.size() > 0) {
            mData.addAll(0, list);
            notifyDataSetChanged();
            downloadVoiceFile(list);
        }
    }

    public void addAdapterData(MessageEntity entity) {
        addData(entity);
        if (entity.msgType == MsgType.MSG_TYPE_VOICE.getNumber()) {
            ArrayList<MessageEntity> list = new ArrayList<>();
            list.add(entity);
            downloadVoiceFile(list);
        }
    }

    public void toggleAdapterData(MessageEntity entity) {
        if (mData.contains(entity)) {
            notifyDataSetChanged();
        } else {
            addAdapterData(entity);
        }
    }

    public void addAdapterData(List<MessageEntity> list) {
        addData(list);
        downloadVoiceFile(list);
    }

    @Override
    protected int getDefItemViewType(int position) {
        MessageEntity entity = mData.get(position);
        if (entity.cmd == Command.COMMAND_CANCEL_MSG_REQ.getNumber()) {
            return MSG_NOTIFICATION;
        }
        boolean isSelf = ImHelper.isSelf(entity.from);
        switch (MsgType.valueOf(entity.msgType)) {
            case MSG_TYPE_TEXT:
                return isSelf ? MSG_SEND_TEXT : MSG_RECEIVE_TEXT;
            case MSG_TYPE_IMG:
                return isSelf ? MSG_SEND_IMAGE : MSG_RECEIVE_IMAGE;
            case MSG_TYPE_VOICE:
                return isSelf ? MSG_SEND_AUDIO : MSG_RECEIVE_AUDIO;
            case MSG_TYPE_VIDEO:
                return isSelf ? MSG_SEND_VIDEO : MSG_RECEIVE_VIDEO;
            default:
                return MSG_UNKNOW;
        }
    }

    @Override
    protected BaseRecyclerHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case MSG_RECEIVE_TEXT:
            case MSG_SEND_TEXT:
            case MSG_SEND_IMAGE:
            case MSG_RECEIVE_IMAGE:
            case MSG_SEND_AUDIO:
            case MSG_RECEIVE_AUDIO:
            case MSG_SEND_VIDEO:
            case MSG_RECEIVE_VIDEO:
            case MSG_NOTIFICATION:
            case MSG_UNKNOW:
                return createBaseViewHolder(getItemView(viewType, parent));
        }
        return super.onCreateDefViewHolder(parent, viewType);
    }


    @Override
    public void onBindViewHolder(BaseRecyclerHolder holder, int position) {
        switch (holder.getItemViewType()) {
            case MSG_SEND_TEXT:
                convertText(holder, getItem(position - getHeaderLayoutCount()), true);
                break;
            case MSG_RECEIVE_TEXT:
                convertText(holder, getItem(position - getHeaderLayoutCount()), false);
                break;
            case MSG_SEND_IMAGE:
                convertImage(holder, getItem(position - getHeaderLayoutCount()), true);
                break;
            case MSG_RECEIVE_IMAGE:
                convertImage(holder, getItem(position - getHeaderLayoutCount()), false);
                break;
            case MSG_SEND_AUDIO:
                convertAudio(holder, getItem(position - getHeaderLayoutCount()), true);
                break;
            case MSG_RECEIVE_AUDIO:
                convertAudio(holder, getItem(position - getHeaderLayoutCount()), false);
                break;
            case MSG_SEND_VIDEO:
                convertVideo(holder, getItem(position - getHeaderLayoutCount()), true);
                break;
            case MSG_RECEIVE_VIDEO:
                convertVideo(holder, getItem(position - getHeaderLayoutCount()), false);
                break;
            case MSG_NOTIFICATION:
                convertNotification(holder, getItem(position - getHeaderLayoutCount()));
                break;
            case MSG_UNKNOW:
                convertUnknow(holder, getItem(position - getHeaderLayoutCount()));
                break;

        }
        super.onBindViewHolder(holder, position);
    }


    @Override
    protected void convert(BaseRecyclerHolder helper, MessageEntity item) {

    }

    private void convertNotification(BaseRecyclerHolder helper, MessageEntity item) {
        setTimeStatus(helper, item);
        helper.setText(R.id.tvNotification, item.content);
    }

    private void convertUnknow(BaseRecyclerHolder helper, MessageEntity item) {
        setTimeStatus(helper, item);
        helper.setText(R.id.tvNotification, "不支持的消息类型");
    }

    private void convertVideo(BaseRecyclerHolder helper, MessageEntity item, boolean isSelf) {
        setTimeStatus(helper, item);
        setAvatar(helper, item, isSelf);
        setNick(helper, item, isSelf);

    }

    private void convertAudio(final BaseRecyclerHolder helper, final MessageEntity item, boolean isSelf) {
        setTimeStatus(helper, item);
        setAvatar(helper, item, isSelf);
        setNick(helper, item, isSelf);
        setProgress(helper, item);
        setStatus(helper, item);


        try {
            VoiceBean bean = JSON.parseObject(item.content, VoiceBean.class);
            if (bean != null) {
                int seconds = (int) JSON.parseObject(item.content, VoiceBean.class).voiceRecordingSeconds;
                seconds = seconds > 0 ? seconds : 1;
                helper.setText(R.id.tvDuration, String.format("%1$s%2$s", seconds, "''"));
                TextView view = helper.getView(R.id.tvDuration);
                float v = seconds / 60f;
                int size = AutoUtils.getPercentWidthSize((int) (350 * (v > 1 ? 1 : v)));
                view.setWidth(CommonTools.dip2px(WrapperApplication.getInstance(), 25) + size);
            }
        } catch (Exception e) {
            LogUtils.info("--> " + item.content);
            LogUtils.error(e);
            TextView view = helper.getView(R.id.tvDuration);
            helper.setText(R.id.tvDuration, String.format("%1$s%2$s", 1, "''"));
            view.setWidth(CommonTools.dip2px(WrapperApplication.getInstance(), 25));
        }
        helper.addOnClickListener(R.id.rlAudio);
    }

    private void convertImage(BaseRecyclerHolder helper, final MessageEntity item, boolean isSelf) {
        setTimeStatus(helper, item);

        setAvatar(helper, item, isSelf);
        setNick(helper, item, isSelf);
        setProgress(helper, item);
        String url = item.content;
        if (url.startsWith("http") && !url.startsWith("https") && !url.startsWith("http://")) {
            url = "http://" + url.substring(6, url.length());
        }
        Glide.with(mContext).load(url).apply(new RequestOptions().placeholder(R.drawable.placeholder_square).error(R.drawable.placeholder_square_failed)).into((ImageView) helper.getView(R.id.bivPic));
        helper.getView(R.id.bivPic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(ImagePreviewActivity.getIntent(mContext, item.content));
            }
        });
    }

    private void convertText(BaseRecyclerHolder helper, MessageEntity item, boolean isSelf) {
        setTimeStatus(helper, item);
        setAvatar(helper, item, isSelf);
        setNick(helper, item, isSelf);
        helper.addOnClickListener(R.id.tvText);
        helper.addOnLongClickListener(R.id.tvText);
        MoonUtils.identifyFaceExpression(mContext, helper.getView(R.id.tvText), item.content, ImageSpan.ALIGN_BOTTOM);
    }

    private void setNick(BaseRecyclerHolder helper, MessageEntity entity, boolean isSelf) {
        if (isSelf) {
            helper.setVisible(R.id.tvName, false);
        } else {
            helper.setVisible(R.id.tvName, true);
            helper.setText(R.id.tvName, TextUtils.isEmpty(entity.fromNick) ? entity.from : entity.fromNick);
        }
    }

    /**
     * 设置头像
     *
     * @param helper
     * @param entity
     * @param isSelf
     */
    private void setAvatar(BaseRecyclerHolder helper, MessageEntity entity, boolean isSelf) {
        if (isSelf) {
            helper.setImageManager(mContext, R.id.ivAvatar, ImHelper.getSelfAvatar(), R.drawable.placeholder_header);
        } else {
            helper.addOnClickListener(R.id.ivAvatar);
            helper.setImageManager(mContext, R.id.ivAvatar, entity.fromAvatar, R.drawable.placeholder_header);
        }
    }

    /**
     * 显示时间
     *
     * @param entity
     * @return
     */
    private boolean isShowTime(MessageEntity entity) {
        int i = getData().indexOf(entity);
        if (i == 0) {
            return true;
        }
        MessageEntity preEntity = getData().get(i - 1);
        return entity.createTime - preEntity.createTime > 5 * 60 * 1000;
    }


    private void setTimeStatus(BaseRecyclerHolder helper, MessageEntity entity) {
        if (isShowTime(entity)) {
            helper.setGone(R.id.tvTime, true);
            helper.setText(R.id.tvTime, ImHelper.formatTime(entity.createTime));
        } else {
            helper.setGone(R.id.tvTime, false);
        }
    }

    private void setProgress(BaseRecyclerHolder helper, MessageEntity entity) {
        if (entity.isSending == 1) {
            helper.setVisible(R.id.pbSending, true);
        } else {
            helper.setVisible(R.id.pbSending, false);
        }
    }

    private void setStatus(final BaseRecyclerHolder helper, final MessageEntity entity) {
        if (entity.isFailed == 1) {
            helper.setVisible(R.id.llError, true);
        } else {
            helper.setVisible(R.id.llError, false);
        }

        helper.getView(R.id.llError).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (entity.msgType == MsgType.MSG_TYPE_VOICE.getNumber()) {
//                    downloadAndPlayVoice(helper, entity, mData.indexOf(entity));
//                }

            }
        });
    }

    public void downloadVoiceFile(List<MessageEntity> list) {
        if (list != null && list.size() > 0) {
            for (MessageEntity entity : list) {
                if (entity.msgType == MsgType.MSG_TYPE_VOICE.getNumber()) {
                    File localFile = null;
                    if (!TextUtils.isEmpty(entity.voiceLocalPath)) {
                        localFile = new File(entity.voiceLocalPath);
                    }
                    File voiceFile = null;
                    if (localFile != null && localFile.exists()) {
                        voiceFile = localFile;
                    } else {
                        VoiceBean bean = JSON.parseObject(entity.content, VoiceBean.class);
                        if (bean != null && !TextUtils.isEmpty(bean.voicePath)) {
                            voiceFile = AudioRecorderManager.getCachedVoiceFileByUrl(WrapperApplication.getInstance(), bean.voicePath);

                            if (voiceFile == null || !voiceFile.exists()) {
                                DownloadManager.getInstance(WrapperApplication.getInstance()).downloadVoice(bean.voicePath, new DownloadManager.Callback() {
                                    @Override
                                    public void onSuccess(File file) {
                                        LogUtils.info("--> 下载完成 " + file.getAbsolutePath());
                                    }

                                    @Override
                                    public void onFailure() {
                                        LogUtils.info("--> 下载失败 ");
                                    }
                                });
                            }
                        }
                    }

                }

            }
        }
    }


    /**
     * 下载录音文件，并设置录音时长
     *
     * @param entity
     */
    private void downloadAndPlayVoice(final BaseRecyclerHolder helper, final MessageEntity entity, final int position) {
        File localFile = null;
        if (!TextUtils.isEmpty(entity.voiceLocalPath)) {
            localFile = new File(entity.voiceLocalPath);
        }
        File voiceFile = null;
        if (localFile != null && localFile.exists()) {
            voiceFile = localFile;
        } else {
            VoiceBean bean = JSON.parseObject(entity.content, VoiceBean.class);
            if (bean != null && !TextUtils.isEmpty(bean.voicePath)) {
                voiceFile = AudioRecorderManager.getCachedVoiceFileByUrl(WrapperApplication.getInstance(), bean.voicePath);
                if (voiceFile == null || !voiceFile.exists()) {
                    DownloadManager.getInstance(WrapperApplication.getInstance()).downloadVoice(bean.voicePath, new DownloadManager.Callback() {
                        @Override
                        public void onSuccess(File file) {
                            mData.get(position).isFailed = 0; //下载成功
                            notifyDataSetChanged();

                            if (currentPosition == position) {
                                playVoice(helper, file, position);
                            }
                            LogUtils.info("--> 下载完成 " + file.getAbsolutePath());
                        }

                        @Override
                        public void onFailure() {
                            mData.get(position).isFailed = 1;  //下载失败
                            notifyDataSetChanged();
                            LogUtils.info("--> 下载失败 ");
                        }
                    });
                }
            }
        }

        if (voiceFile != null && voiceFile.exists()) {
            playVoice(helper, voiceFile, position);
        }
    }

    private void playVoice(final BaseRecyclerHolder helper, File voiceFile, int position) {
        final MessageEntity entity = mData.get(position);
        final View view = helper.getView(R.id.ivAudio);
        final boolean isSelf = ImHelper.isSelf(entity.from);
        setPlayVoiceAnim(view, true, isSelf);
        AudioPlayerManager.playSound(voiceFile.getAbsolutePath(), new AudioPlayerManager.Callback() {
            @Override
            public void onError() {
                showToast("语音加载失败");
                setPlayVoiceAnim(view, false, isSelf);
            }

            @Override
            public void onCompletion() {
                setPlayVoiceAnim(view, false, isSelf);
            }
        });
    }

    private void setPlayVoiceAnim(View view, boolean isPlay, boolean isSelf) {
        if (view != null && view instanceof ImageView) {
            Drawable drawable = view.getBackground();
            if (drawable != null && drawable instanceof AnimationDrawable) {
                if (isPlay) {
                    ((AnimationDrawable) drawable).start();
                } else {
                    view.clearAnimation();
                    ((AnimationDrawable) drawable).stop();
                    ((AnimationDrawable) drawable).selectDrawable(0);
                }
            } else {
                view.setBackgroundResource(isSelf ? R.drawable.audio_animation_right_list : R.drawable.audio_animation_left_list);
            }
        }
    }

    private void playAudioAnim(View parent, boolean isPlay) {
        if (parent != null) {
            View view = parent.findViewById(R.id.ivAudio);
            if (view != null && view instanceof ImageView) {
                Drawable drawable = view.getBackground();
                if (drawable != null && drawable instanceof AnimationDrawable) {
                    if (isPlay) {
                        ((AnimationDrawable) drawable).start();
                    } else {
                        view.clearAnimation();
                        ((AnimationDrawable) drawable).stop();
                        ((AnimationDrawable) drawable).selectDrawable(0);
                    }
                }
            }
        }
    }

    private void showToast(String msg) {
        ToastView.showToastInCenter(WrapperApplication.getInstance(), msg);
    }


    public void playAudio(final View view, final MessageEntity entity, final int position) {
        currentPosition = position;
        File localFile = null;
        if (!TextUtils.isEmpty(entity.voiceLocalPath)) {
            localFile = new File(entity.voiceLocalPath);
        }
        File voiceFile = null;
        if (localFile != null && localFile.exists()) {
            voiceFile = localFile;
        } else {
            VoiceBean bean = JSON.parseObject(entity.content, VoiceBean.class);
            if (bean != null && !TextUtils.isEmpty(bean.voicePath)) {
                voiceFile = AudioRecorderManager.getCachedVoiceFileByUrl(WrapperApplication.getInstance(), bean.voicePath);
                if (voiceFile == null || !voiceFile.exists()) {
                    DownloadManager.getInstance(WrapperApplication.getInstance()).downloadVoice(bean.voicePath, new DownloadManager.Callback() {
                        @Override
                        public void onSuccess(File file) {
                            entity.isFailed = 0; //下载成功
                            notifyDataSetChanged();
                            if (currentPosition == position) {
                                playAudio(view, file);
                            }
                        }

                        @Override
                        public void onFailure() {
                            entity.isFailed = 1;  //下载失败
                            notifyDataSetChanged();
                            LogUtils.info("--> 下载失败 ");
                        }
                    });
                }
            }
        }

        if (voiceFile != null && voiceFile.exists()) {
            playAudio(view, voiceFile);
        }
    }

    private void playAudio(final View view, final File file) {
        AudioPlayManager.getInstance().startPlay(WrapperApplication.getInstance(), Uri.fromFile(file), new IAudioPlayListener() {
            @Override
            public void onStart(Uri var1) {
                playAudioAnim(view, true);
            }

            @Override
            public void onStop(Uri var1) {
                playAudioAnim(view, false);
            }

            @Override
            public void onComplete(Uri var1) {
                playAudioAnim(view, false);
            }
        });
    }
}
